<template>
  <div class="my-container mt-4">
    <h3 class="mb-4">
      按标签分类
    </h3>
    <hr class="divider">

    <div
      v-for="(items, label) in groupedMaterials"
      :key="label"
      class="card shadow-sm border-0 mb-4"
    >
      <div
        class="card-header border-bottom-0 rounded-top d-flex align-items-center"
        style="background-color: #104f91; color: #fff"
      >
        <strong class="fs-5">标签：{{ label || '未分组' }}</strong>
      </div>
      <ul class="list-group list-group-flush">
        <li
          v-for="(item, index) in items"
          :key="index"
          class="list-group-item d-flex justify-content-between align-items-center"
          style="transition: background 0.2s; border: none"
          @mouseover="(e) => (e.currentTarget.style.background = '#f8f9fa')"
          @mouseleave="(e) => (e.currentTarget.style.background = '')"
        >
          <div class="d-flex align-items-center flex-row flex-grow-1">
            <span style="font-size: 1.07rem">📄 {{ item.materialName }}</span>
            <small
              class="fw-semibold ms-auto text-muted mt-1 me-3"
            >上传于 {{ new Date(item.uploadTime).toLocaleString() }}</small>
          </div>
          <div class="d-flex gap-2">
            <button
              v-if="userRole === 'student'"
              class="btn btn-sm btn-primary btn-download"
              @click="downloadMaterial(item)"
            >
              下载
            </button>
            <button
              v-if="userRole === 'teacher'"
              class="btn btn-sm btn-danger btn-delete"
              @click="deleteMaterial(item)"
            >
              删除
            </button>
          </div>
        </li>
        <li
          v-if="items.length === 0"
          class="list-group-item text-center text-muted bg-light border-0"
        >
          暂无资料
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  import { useRoute } from 'vue-router'
  import axios from 'axios'
  import emitter from '@/eventBus'

  import { useRouter } from 'vue-router'
  import { useUserStore } from '@/stores/userStore'

  const userRole = ref('') // 保存后端返回的角色
  const router = useRouter()
  const userStore = useUserStore()
  const userId = userStore.user?.userId || ''
  async function fetchUserRole() {
    try {
      const res = await axios.get('/api/exercises/role', {
        params: {
          courseId,
          userId,
        },
      })
      userRole.value = res.data
      console.log('身份识别结果:', userRole.value)
    } catch (err) {
      console.error('获取用户身份失败', err)
      userRole.value = 'undefined'
    }
  }
  onMounted(fetchUserRole)

  const route = useRoute()
  const courseId = route.params.id

  const materials = ref([])
  const groupedMaterials = ref({})

  async function fetchLabelsAndMaterials() {
    try {
      const res = await axios.get(`/api/materials/course/${courseId}`)
      materials.value = res.data

      // 分组
      groupedMaterials.value = groupByLabel(materials.value)
    } catch (err) {
      console.error('获取资料失败', err)
    }
  }
  onMounted(async () => {
    fetchLabelsAndMaterials()

    emitter.on('material-uploaded', handleMaterialUploaded)
  })
  onUnmounted(() => {
    emitter.off('material-uploaded', handleMaterialUploaded)
  })
  function handleMaterialUploaded(payload) {
    console.log('收到上传成功事件:', payload)
    fetchLabelsAndMaterials() // 你已有的刷新逻辑
  }
  // 工具函数：按标签分组
  function groupByLabel(data) {
    return data.reduce((acc, item) => {
      const label = item.materialLabel || '未分组'
      if (!acc[label]) acc[label] = []
      acc[label].push(item)
      return acc
    }, {})
  }

  // 下载
  async function downloadMaterial(item) {
    try {
      const res = await axios.get(`/api/materials/${item.materialId}/download`, {
        responseType: 'blob',
      })

      const blob = new Blob([res.data])
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = item.materialName || 'downloaded_file'
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    } catch (err) {
      alert('下载失败：' + err.message)
    }
  }

  // 删除
  async function deleteMaterial(item) {
    const ok = confirm(`确认删除：${item.materialName} 吗？`)
    if (!ok) return
    try {
      await axios.delete(`/api/materials/${item.materialId}`)
      materials.value = materials.value.filter((m) => m.materialId !== item.materialId)
      groupedMaterials.value = groupByLabel(materials.value)
    } catch (err) {
      alert('删除失败：' + err.message)
    }
  }
</script>

<style scoped>
  .mb-4 {
    text-align: left;
  }

  .card {
    border: 1px solid #dee2e6;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    transform-origin: center center;
  }

  .card-header {
    text-align: left;
  }
  .my-container {
    width: 80vw;
    margin: 0 auto;
  }
  .divider {
    height: 1px;
    background-color: #ccc;
    margin: 16px 0;
  }

  .btn-download {
    background-color: #28a745; /* 绿色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-download:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(40, 167, 69, 0.3);
  }

  .btn-delete {
    background-color: #dc3545; /* 红色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-delete:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
  }
</style>
